package com.zwh.mangomall.controller;

import com.google.gson.Gson;
import com.zwh.mangomall.pojo.MangoUser;
import com.zwh.mangomall.service.UserInfoService;
import com.zwh.mangomall.service.ex.LoginException;
import com.zwh.mangomall.util.IpUtil;
import com.zwh.mangomall.util.ResultCode;
import com.zwh.mangomall.util.ResultMsg;
import com.zwh.mangomall.util.TokenUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sun.jmx.snmp.ThreadContext.contains;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserInfoController {

    @Autowired
    UserInfoService userInfoService;

    @RequestMapping(value = "/register", method = {RequestMethod.POST})
    public String register(HttpServletRequest request, @RequestBody String body){

        ResultMsg resultMsg = new ResultMsg();

        JSONObject jsonObject = JSONObject.fromObject(body);

        jsonObject.put("ip", IpUtil.getIp(request));

        if(userInfoService.insertUserInfo(jsonObject)){
            resultMsg.setCode(ResultCode.SUCCESS);
            resultMsg.setMsg("注册成功");
        }

        return new Gson().toJson(resultMsg);
    }

    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public String login(HttpServletRequest req, HttpServletResponse resp, @RequestBody String body){
        ResultMsg resultMsg = new ResultMsg();

        JSONObject jsonObject = JSONObject.fromObject(body);

        HttpSession session = req.getSession();

        MangoUser mangoUser = userInfoService.userLogin(jsonObject);
        if(mangoUser != null){
            String password = mangoUser.getPassword();
            mangoUser.setPassword(null);
            // 向Session添加用户的登录状态
            session.setAttribute("user", mangoUser);
            if(jsonObject.containsKey("type")){
                Object[] types = JSONArray.fromObject(jsonObject.getJSONArray("type")).toArray();
                List<Object> typeList = Arrays.asList(types);
                if(typeList.contains("自动登录")){
                    Cookie cookie=new Cookie("autoLogin",mangoUser.getPhone()+"_#_"+password);
                    // 设置cookie的有效时间
                    cookie.setMaxAge(24*60*60); // 24小时，可读性好
                    // 设置Cookie的路径
                    cookie.setPath("/");
                    // 发送cookie
                    resp.addCookie(cookie);
                }else if (!typeList.contains("自动登录") && typeList.contains("记住密码")){
                    Cookie cookie=new Cookie("rememberPwd",mangoUser.getPhone()+"_#_"+password);
                    cookie.setMaxAge(24*60*60);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                }else if(!typeList.contains("自动登录") && !typeList.contains("记住密码")){
                    // 未勾选,删除自动登录Cookie
                    Cookie autoCookie=new Cookie("autoLogin","");
                    Cookie rememberCookie=new Cookie("rememberPwd","");

                    autoCookie.setMaxAge(0); // 删除cookie
                    rememberCookie.setMaxAge(0);

                    autoCookie.setPath("/");
                    rememberCookie.setPath("/");

                    resp.addCookie(autoCookie);
                    resp.addCookie(rememberCookie);
                }
            }
            resultMsg.setCode(ResultCode.SUCCESS);
            resultMsg.setMsg("登录成功");
            resultMsg.setData(mangoUser);
        }
        return new Gson().toJson(resultMsg);
    }

    @RequestMapping(value = "logout", method = {RequestMethod.POST})
    public String logout(HttpServletRequest req, HttpServletResponse resp){
        ResultMsg resultMsg = new ResultMsg();

        HttpSession session = req.getSession();
        // 清空Session中的数据，销毁session
        session.invalidate();
        // 删除自动登录的Cookie
        Cookie cookie=new Cookie("autoLogin","");
        cookie.setMaxAge(0); // 删除cookie
        cookie.setPath("/");
        resp.addCookie(cookie);
        // 重定向到登录页面
        try {
            resp.sendRedirect("/login");
        } catch (IOException e) {
            throw new LoginException("退出失败");
        }

        return new Gson().toJson(resultMsg);
    }

    @RequestMapping(value = "/resetPassword")
    public String resetPassword(@RequestBody String body){
        return null;
    }
}
